Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

HTML5 Data and Services Cookbook
HTML5 Data and Services Cookbook
HTML5 Data and Services Cookbook
Ebook1,093 pages6 hours

HTML5 Data and Services Cookbook

Rating: 5 out of 5 stars

5/5

()

Read preview

About this ebook

A practical approach with hands on recipes to learn more about HTML5 Data and Services, its features and techniques when building websites or web applications.This book is for programmers and developers who work with a lot of backend code and want to get fast tracked into the world of HTML5 and Javascript. It is also for JavaScript developers who would like to update their knowledge with new techniques and capabilities made possible with HTML5.Some experience in HTML and jQuery is assumed.
LanguageEnglish
Release dateSep 3, 2013
ISBN9781783559299
HTML5 Data and Services Cookbook

Related to HTML5 Data and Services Cookbook

Related ebooks

Programming For You

View More

Related articles

Reviews for HTML5 Data and Services Cookbook

Rating: 5 out of 5 stars
5/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    HTML5 Data and Services Cookbook - Gorgi Kosev

    Table of Contents

    HTML5 Data and Services Cookbook

    Credits

    About the Authors

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers and more

    Why Subscribe?

    Free Access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Display of Textual Data

    Introduction

    Rounding numbers for display

    Getting ready

    How to do it...

    How it works…

    There's more...

    Padding numbers

    Getting ready

    How to do it...

    How it works…

    There's more...

    Displaying metric and imperial measurements

    Getting ready

    How to do it...

    How it works...

    Displaying formatted dates in the user's time zone

    Getting ready

    How to do it...

    How it works…

    There's more...

    Displaying the dynamic time that has elapsed

    Getting ready

    How to do it...

    How it works…

    There's more...

    Displaying Math

    Getting ready

    How to do it...

    How it works…

    There's more...

    Creating an endless scrolling list

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating a sortable paginated table

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating multiple-choice filters

    Getting ready

    How to do it...

    How it works...

    Creating range filters

    Getting ready

    How to do it...

    How it works...

    Creating combined complex filters

    Getting ready

    How to do it...

    How it works...

    There's more...

    Displaying code in HTML

    Getting ready

    How to do it...

    How it works…

    There's more…

    Rendering Markdown

    How to do it...

    How it works...

    There's more...

    Autoupdating fields

    Getting ready

    How to do it...

    How it works…

    There's more...

    2. Display of Graphical Data

    Introduction

    Creating a line chart

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating a bar chart

    Getting ready

    How to do it...

    How it works...

    Creating a pie chart

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating an area chart

    Getting ready

    How to do it...

    How it works...

    There's more...

    Displaying combined charts

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating a bubble chart

    How to do it...

    How it works...

    There's more...

    Showing a map with a marked location

    How to do it...

    How it works...

    Showing a map with a path

    How to do it...

    How it works...

    Displaying gauges

    How to do it...

    How it works...

    Displaying a tree

    Getting ready

    How to do it...

    How it works…

    There's more...

    LED scoreboard using web fonts

    Getting ready

    How to do it...

    How it works…

    There's more...

    3. Animated Data Display

    Introduction

    Making a motion chart

    Getting ready

    How to do it...

    How it works...

    There's more...

    Displaying a force directed graph

    Getting ready

    How to do it...

    How it works...

    There's more...

    Making a live range chart filter

    Getting ready

    How to do it...

    How it works...

    Making an image carousel

    Getting ready

    How to do it...

    How it works...

    Zooming and panning a chart

    Getting ready

    How to do it...

    How it works...

    Using the web notifications API

    Getting ready

    How to do it...

    How it works...

    Creating interactive Geo charts from a dataset

    Getting ready

    How to do it...

    How it works...

    There's more...

    4. Using HTML5 Input Components

    Introduction

    Using the text input field

    How to do it...

    How it works...

    There's more...

    Using textarea

    How to do it...

    How it works...

    Inputting dates

    How to do it...

    How it works...

    Inputting time

    How to do it...

    How it works...

    Telephone input

    How to do it...

    How it works...

    There's more...

    Range input field

    How to do it...

    How it works...

    There 's more...

    Color picker input

    How to do it...

    How it works...

    Using single-choice dropdowns

    How to do it...

    How it works...

    There's more...

    Using multiple-choice select lists

    How to do it...

    How it works...

    Getting geographical location input

    How to do it...

    How it works...

    There's more...

    Using file inputs at the client side

    How to do it...

    How it works...

    There's more...

    Using a drag-and-drop file area

    How to do it...

    How it works...

    There's more...

    5. Custom Input Components

    Introduction

    Using contentEditable for basic rich text input

    How to do it...

    How it works...

    Advanced rich text input

    Getting ready

    How to do it...

    How it works...

    There's more…

    Creating a drop-down menu

    Getting ready

    How to do it...

    How it works...

    Creating custom dialogs

    Getting ready

    How to do it...

    How it works...

    Creating autocomplete for input

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating a custom single-selection list

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating a multiple-selection list

    Getting ready

    How to do it...

    How it works...

    Geographic location input using maps

    Getting ready

    How to do it...

    How it works...

    6. Data Validation

    Introduction

    Validating text by length

    How to do it...

    How it works...

    There's more...

    Validating numbers by range

    How to do it...

    How it works...

    Using the built-in pattern validation

    How to do it...

    How it works...

    There's more...

    Advanced use of built-in constraints and custom validations

    How to do it...

    How it works...

    There's more...

    Calculating password strength

    Getting ready

    How to do it...

    How it works...

    Validating US zip codes

    Getting ready

    How to do it...

    How it works...

    Using asynchronous server-side validation

    Getting ready

    How to do it...

    How it works...

    Combining client-side and server-side validation

    Getting ready

    How to do it...

    How it works...

    7. Data Serialization

    Introduction

    Deserializing JSON to JavaScript objects

    How to do it...

    How it works...

    There's more...

    Serializing objects to a JSON string

    How to do it...

    How it works...

    There's more...

    Decoding base64 encoded binary data

    Getting ready

    How to do it...

    How it works...

    Encoding binary data or text into base64

    How to do it...

    How it works...

    There's more...

    Serializing binary data into JSON

    How to do it...

    How it works...

    There's more...

    Serializing and deserializing cookies

    Getting ready

    How to do it...

    How it works...

    There's more...

    Serializing a form into request strings

    How to do it...

    How it works...

    There's more...

    Reading XML documents with DOMParser

    How to do it...

    How it works...

    Serialization of XML document at the client side

    How to do it...

    How it works...

    There's more...

    8. Communicating with Servers

    Creating an HTTP GET request to fetch JSON

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating a request with custom headers

    Getting ready

    How to do it...

    How it works...

    There's more...

    Versioning your API

    Getting ready

    How to do it...

    How it works...

    There's more...

    Fetching JSON data with JSONP

    Getting ready

    How to do it...

    How it works...

    There's more...

    Reading XML data from server

    Getting ready

    How to do it...

    How it works...

    There's more...

    Using the FormData interface

    Getting ready

    How to do it...

    How it works...

    Posting a binary file to the server

    Getting ready

    How to do it...

    How it works...

    There's more…

    Creating an SSL connection with Node.js

    Getting ready

    How to do it...

    How it works...

    There's more...

    Making real-time updates with Ajax Push

    Getting ready

    How to do it...

    How it works...

    There's more...

    Exchanging real-time messages using WebSockets

    Getting ready

    How to do it...

    How it works...

    9. Client-side Templates

    Introduction

    Rendering objects using Handlebars

    Getting ready

    How to do it...

    How it works...

    Rendering objects using EJS

    Getting ready

    How to do it...

    How it works...

    There's more...

    Rendering objects using Jade

    Getting ready

    How to do it...

    How it works...

    Rendering arrays using Handlebars

    Getting ready

    How to do it...

    How it works...

    Rendering arrays using EJS

    Getting ready

    How to do it...

    How it works...

    There's more...

    Rendering arrays using Jade

    Getting ready

    How to do it...

    How it works...

    There's more...

    Simplifying templates with helpers in Handlebars

    Getting ready

    How to do it...

    How it works...

    Reusing templates with partials in Handlebars

    Getting ready

    How to do it...

    How it works...

    There's more...

    Reusing templates with partials in EJS

    Getting ready

    How to do it...

    How it works...

    There is more...

    Using filters in Jade

    Getting ready

    How to do it...

    How it works...

    Using mixins in Jade

    Getting ready

    How to do it...

    How it works...

    Using layouts and blocks in Jade

    Getting ready

    How to do it...

    How it works...

    10. Data Binding Frameworks

    Introduction

    Creating a basic Angular view with data binding

    Getting ready

    How to do it...

    How it works...

    There's more...

    Rendering lists and using Angular controllers

    How to do it...

    How it works...

    There's more...

    Routing, filters, and backend services in Angular

    How to do it...

    How it works...

    There's more…

    Using Angular's client-side validation

    How to do it...

    How it works...

    Making a chart component with Angular directives

    Getting ready

    How to do it...

    How it works...

    There's more…

    Structuring applications for Meteor.js

    Getting ready

    How to do it...

    How it works...

    There's more...

    Reactive programming and data in Meteor.js

    Getting ready

    How to do it...

    How it works...

    There's more...

    Live HTML and user-specific data in Meteor.js

    Getting ready

    How to do it...

    How it works...

    There's more...

    Security mechanisms in Meteor.js

    Getting ready

    How to do it...

    How it works...

    There's more...

    11. Data Storage

    Introduction

    Data URI

    Getting ready

    How to do it...

    How it works...

    There's more...

    Session and local storage

    Getting ready

    How to do it...

    How it works...

    There's more...

    Reading data from files

    How to do it...

    How it works...

    There's more...

    Using IndexedDB

    How to do it...

    How it works...

    There's more...

    Limits of the storage and how to ask for more

    How to do it...

    How it works...

    There's more...

    Manipulating the browser history

    Getting ready

    How to do it...

    How it works...

    12. Multimedia

    Introduction

    Playing audio files

    Getting ready

    How to do it...

    How it works...

    Playing video files

    Getting ready

    How to do it...

    How it works...

    There's more...

    Customizing controls for media elements

    Getting ready

    How to do it...

    How it works...

    Adding text to your video

    Getting ready

    How to do it...

    How it works...

    There's more...

    Embedding multimedia

    Getting ready

    How to do it...

    How it works...

    There's more...

    Converting text to speech using HTML5 audio

    Getting ready

    How to do it...

    How it works...

    There's more..

    A. Installing Node.js and Using npm

    Introduction

    Installing Node.js

    Using npm

    Installing a local package

    Installing a global package

    B. Community and Resources

    WHATWG

    World Wide Web Consortium

    Other resources

    Index

    HTML5 Data and Services Cookbook


    HTML5 Data and Services Cookbook

    Copyright © 2013 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: August 2013

    Production Reference: 2270813

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78355-928-2

    www.packtpub.com

    Cover Image by Jarosław Blaminsky (<milak6@wp.pl>)

    Credits

    Authors

    Gorgi Kosev

    Mite Mitreski

    Reviewers

    Rade Despodovski

    Santiago Martín-Cleto

    Kevin Roast

    Ljubomir Zivanovic

    Acquisition Editor

    Mary Nadar

    Lead Technical Editor

    Anila Vincent

    Technical Editors

    Dipika Gaonkar

    Kapil Hemnani

    Krishnaveni Haridas

    Dennis John

    Anita Nayak

    Project Coordinator

    Hardik Patel

    Proofreader

    Clyde Jenkins

    Indexer

    Rekha Nair

    Graphics

    Sheetal Aute

    Production Coordinator

    Arvindkumar Gupta

    Cover Work

    Arvindkumar Gupta

    About the Authors

    Gorgi Kosev is the lead software engineer at CreationPal, where he currently works on development of mobile and desktop HTML5 applications, as well as cloud solutions based on Node.js. He is also responsible for the selection and development of the technology stack used in CreationPal products, such as SportyPal and Appzer for Google Docs.

    He completed his graduation in Electrical Engineering from University of Ss. Cyril and Methodius in 2008, and his Masters in Intelligent Information Systems in 2011. His research interests includes collaborative computer systems and machine learning.

    In his spare time, he enjoys sharing code and hardware hacks with members of the local hack lab and playing the piano.

    I would like to thank Svetle for her patience, support, and understanding during the restless nights and weekends spent writing this book.

    Mite Mitreski works on custom enterprise application development with primary focus on Java and JVM-based solutions. He has worked as a programming course trainer in the past. He is deeply involved in activities surrounding development groups in Macedonia, where he is currently the JUG Leader of Java User Group, Macedonia. Mite has a great passion for free and open source software, open data formats, and the open web. Occasionally, he writes at his blog at http://blog.mitemitreski.com and can be reached on Twitter, his Twitter handle being @mitemitreski.

    I would first like to thank my brother Stojan, who has been my inspiration throughout the years and was always someone to look up to. Thanks also 
to my great parents who raised me up to the person I'm today. I would also like to thank my girlfriend Marija and all the friends and colleagues at Netcetera who had to put up with me while I was away or half present. Thanks to all the reviewers, as well as the team at Packt Publishing who made the book happen. And last but not the least, thanks to W3C, the Mozilla team, Apache Software Foundation, and all of you who work on open technologies and make or keep the Internet free and open so the 
rest of us can enjoy it each day.

    About the Reviewers

    Rade Despodovski graduated from the Faculty of Electrical Engineering and Information Technologies in Skopje, Macedonia, in the year 2011 as a software engineer. He has been developing and using Microsoft technologies for eight years. In the last two years, his professional efforts have been concentrated on web technologies, in particular, using HTML5 and JavaScript. At present, his biggest interests lay in the development of multiplatform applications based on open-source technologies. Contact Rade at <rade.despodovski@gmail.com>.

    Santiago Martín-Cleto started his career as a web designer for an outstanding Spanish media group in 1999. Passionate about design and code, he considers himself as a web standards and open source advocate. He has been involved in huge projects for mass media and financial corporations as a contributor to launch start-ups. As a front-end developer, he is specialized in high traffic websites performance issues.

    He has also reviewed HTML5 Enterprise Application Development, published by Packt Publishing.

    Kevin Roast is a front-end software developer with 15 years professional experience and a lifelong interest in computer science and computer graphics. He has developed software for several companies and is a founding developer at Alfresco Software Ltd. He is very excited by the prospect of the HTML5 standardization of the web and the progress of web-browser software in recent years. He was also the co-author of a book Professional Alfresco: Practical Solutions for Enterprise Content Management, Wrox and has been a technical reviewer on several HTML5 and software development related books.

    I would like to thank my wife for putting up with me tapping away in the evenings reviewing book chapters and to my three lovely kids Ben, Alex, 
and Izzy.

    Ljubomir Zivanovic is a senior software developer at Netcetera and lead of Microsoft Competence Center within the company. He has over a decade of experience in the software industry, mainly focused on web stack and front-end technologies that affect UX in every way. One of the founders of the Macedonian .NET User Group, devoted husband and father, and a passionate amateur photographer.

    I would like to thank both the authors of this book for giving me the opportunity to work on this book as a reviewer; it was an extraordinary experience for me. I would also like to express my gratitude to my beloved wife for giving me the support and understanding what every passionate developer can only think of.

    www.PacktPub.com

    Support files, eBooks, discount offers and more

    You might want to visit www.PacktPub.com for support files and downloads related to your book.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    http://PacktLib.PacktPub.com

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

    Why Subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print and bookmark content

    On demand and accessible via web browser

    Free Access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

    Preface

    HTML5 is everywhere, from PCs to tablets, smartphones, and even modern TV sets. The web is the most ubiquitous application platform and information medium. More recently, HTML5 has become a first-class citizen in established operating systems such as Microsoft Windows 8, Firefox OS, and Google Chrome OS.

    Openness is one of the important aspects of the web. HTML5 is one of the primary ways to oppose private and proprietary solutions that force the usage of certain technologies. There is a true revolution happening in the past few years. JavaScript has risen to the lead position in web application development for both server side and client side.

    In the past, it was very common to get half done scripts and poorly written JavaScript, thus the language formed a bad reputation. HTML5 features are already available and widely underused. There is a huge deal of web applications that reinvent the wheel, when there is already a feature in HTML5 that they need.

    This book will get you on the fast track to learning modern HTML5 features. By the end of the book, you should have a solid understanding of JavaScript in the browser and server. On top of that, you will end up creating cool, little applications using new HTML5 technologies, and learn how to adapt your existing applications to use these great new features.

    What this book covers

    Chapter 1, Display of Textual Data, covers what you need to know about displaying text in HTML5. This includes formatting numbers, displaying math formulas, and measurements. Additionally, there are sections on displaying tabular data and rendering Markdown that show some of the everyday development functionality.

    Chapter 2, Display of Graphical Data, begins by covering the creation of charts using the Flot chart library, as well as the more modern data-driven D3.js. Displaying maps with routes and markers is also covered in this chapter.

    Chapter 3, Animated Data Display, explores the creation of animated and interactive visualizations. Most of the chapter visualization are based on D3.js, but there are also examples that start from scratch or use technology such as the notifications API.

    Chapter 4, Using HTML5 Input Components, begins by covering the use of simple text input elements, and moves to the new input types that are added by HTML5. It also covers the use of the new attributes, as well as making more advanced input that uses geolocation or drag-and-drop areas.

    Chapter 5, Custom Input Components, continues with the topics from the preceding chapter, with the main focus shifting to the creation of custom controls that add new functionality, or mimic components available in the desktop applications. This chapter explains how to create controls, such as menus, dialogs, list selection, and rich-text input.

    Chapter 6, Data Validation, introduces the HTML5 way of handling form validation. The chapter will cover validation of text and numbers, built-in validations for e-mail and numbers. Furthermore, it also covers server-side validation with Node.js, and shows how to combine client and server-side validation.

    Chapter 7, Data Serialization, provides an in-depth look into the creation of JSON, base64, and XML from client-side JavaScript, as well as the reverse process of making the JavaScript objects from the formats.

    Chapter 8, Communicating with Servers, gets you started with Node.js and the creation of REST API's. The chapter also contains detailed information on how to make HTTP calls from pure JavaScript, how to handle binary files, as well as communication security.

    Chapter 9, Client-side Templates, introduces the use of the popular client-side template languages Handlebars, EJS, and Jade. It covers and compares the basic uses of these languages, as well as their more advanced features, such as partials, filters, and mixins.

    Chapter 10, Data Binding Frameworks, gets you started with two different types of web frameworks. On the one hand we have Angular, a powerful representative of the many different client-side MVC frameworks, and on the other hand we have Meteor, a reactive framework that cuts down the development time in certain domains.

    Chapter 11, Data Storage, explores the new client-side storage APIs available in HTML5, as well as the new APIs for working with files. These new features enable us to persist data beyond page refresh, and save client-side information that will not be transferred back and forth on each request.

    Chapter 12, Multimedia, covers some of the ways for playing video and audio files in the browser, something that was done by external plugins in the past.

    Appendix A, Installing Node.js and Using npm, gives a simple introduction on installing Node.js and using its package manager npm.

    Appendix B, Community and Resources, contains a short history and references to the main organizations that empower the development of HTML5.

    What you need for this book

    All you need to get started is a modern browser, such as Firefox, Chrome, Safari, Opera, or Internet Explorer 9, a simple text editor such as Notepad++, Emacs, or Vim, and an Internet connection.

    In Chapter 7, Data Serialization and later chapters, you will also need to install Node.js to try out some of the recipes. The installation process is covered in Appendix A, Installing Node.js and Using npm.

    Who this book is for

    This book is for programmers who already have used JavaScript in one way or the other. It's for people who work with a lot of backend code, and want to get up to speed with the world of HTML5 and JavaScript. It's for people who have used copy/paste to patch up a part of a page and want to know more about how things work in the background. It's for JavaScript developers who would like to update their knowledge with new techniques and capabilities made possible with HTML5.

    The book is for both beginners and seasoned developers, assuming that you will have some experience in HTML, JavaScript, and jQuery already, but not necessary an in-depth knowledge.

    Conventions

    In this book, you will find a number of styles of text that distinguish among different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

    Code words in text are shown as follows: The d3.behavior.zoom() method enables us to add automatic zoom functionality to our projection type with the given scale and range of zoom in scaleExtent.

    A block of code is set as follows:

     

        Chart example

     

     

       

    chart style=height:200px;width:800px;>

       

       

       

       

     

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    #carousel {   perspective: 500px;

     

      -webkit-perspective: 500px;

      position:relative; display:inline-block;

      overflow:hidden;

    }

    Any command-line input or output is written as follows:

    Object:   color: #00cc00   data: Array[50]   name: one

    New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: Also we can add an attribute data-placeholder that will contain default text, such as Occupation in our example. If this is not specified, it will default to Select Some Option for single select.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really find useful.

    To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.

    If there is a topic in which you have expertise, and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

    Piracy

    Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors, and our ability to bring you valuable content.

    Questions

    You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.

    Chapter 1. Display of Textual Data

    In this chapter, we're going to cover the following topics:

    Rounding numbers for display

    Padding numbers

    Displaying metric and imperial measurements

    Displaying formatted dates in the user's time zone

    Displaying the dynamic time that has elapsed

    Displaying Math

    Creating an endless scrolling list

    Creating a sortable paginated table

    Creating multiple-choice filters

    Creating range filters

    Creating combined complex filters

    Displaying code in HTML

    Rendering Markdown

    Autoupdating fields

    Introduction

    The most common task related to web application development is the displaying of text. This chapter will cover some of the issues programmers face when displaying data in browsers, and will explain how to tackle the problems in a simple yet effective way, giving several different options for the programmer from which to choose. These examples will contain the rendering of markup or the conversion of other datatypes into plain text.

    Rounding numbers for display

    The second, most common datatype used in applications after text is numbers. There are many different ways of working with numbers, and we will take a look at some of these ways when a given precision is required. The first obvious option is to use the JavaScript Number object wrapper to work with numerical values.

    Getting ready

    The Number object contains the toFixed([digits]) method that can be used to display numbers; here the digits parameter can have a value between 0 and 20. The number will either get rounded automatically if needed, or the number will get padded with additional zeros if necessary. Ok, so let's see it in action.

    How to do it...

    Perform the following steps do demonstrate working with the Number object:

    First, we'll create a list of numbers; note that the numbers have been picked intentionally to illustrate some of the characteristics of the functions:

        var listOfNumbers=

            [1.551, 1.556, 1.5444, 1.5454, 1.5464, 1.615, 1.616, 1.4, 1.446,1.45];

    Iterate the list and display numbers using the .toFixed() method with the digits parameter's values 0, 1, and 2 accordingly:

    for (var i = 0; i < listOfNumbers.length; i++) {

          var number = listOfNumbers[i];

            // iterate over all of the numbers and write to output all the value

          document.write(number + ---

                      + number.toFixed(2) + ---

                      + number.toFixed(1) + ---

                      + number.toFixed() +
    );

        };

    How it works…

    The result retrieved from executing the code will print out the numbers with their respective toFixed representation, which should be straightforward.

    Let's take a look at some of the characteristic values:

    1.616.toFixed(2) will return 1.62

    1.4.toFixed(2) will return 1.40 as expected, adding a trailing zero

    1.5454.toFixed() will return 2, because the default value for toFixed() is 0; this means that no decimal points, and additionally the 0.5 segment is rounded to 1 so the ceiling value is used here

    1.615.toFixed(2) will either return 1.61, ignoring the 0.005 segment, or the floor value will be used

    The toFixed() method works mostly as expected so long as we don't need the higher precision or are only using it to display numbers where the type of rounding is not mission critical.

    Additionally, we cannot rely on toFixed() when we need rounding in cases where we have numbers such as 1.446 and others that fall in the same category; calling 1.446.toFixed(1) would result in inconsistent and unpredictable results.

    There's more...

    There are various ways to solve this. The quick and dirty solution would be to redefine the Number.prototype.toFixed() function, but we encourage you to not do so, as doing this may have side effects that are not apparent. Any redefinition of the functions from the built-in objects is considered an anti-pattern if it is not absolutely essential. The problem arises if another library or a piece of code is using the same function. The other library might expect our redefined function to work a certain way. These types of redefinitions are hard to track; even if we are to add a function instead of redefining it, someone else might do the same thing. For example, say we decided to add some function to the Number object:

    Number.prototype.theFunction = function(arg1,arg2){}

    There are no guarantees that someone else has not already added theFunction to the Number object. We could do additional checks to verify if the function already exists, but we cannot be sure if it does what we want it to do.

    Instead, using a utility function for achieving consistent data would be a better option.

    One way of tackling the problem is to first multiply the number with 10 ^ digits and then call the Math.round(number) method on the result, or you can call Math.ceil(number). For example, if you need to have the value rounded upwards to the nearest integer, use the following:

        function round(number, digits) {

            if(typeof digits === undefined || digits < 0){

              digits = 0;

            }

            var power = Math.pow(10, digits),

            fixed = (Math.round(number * power) / power).toString();

            return fixed;

        };

    Now, as the number gets multiplied with 10 ^ digits and then gets rounded, we do not observe the problems with toFixed(). Note that this method has a different behavior from toFixed() not just in the way of how rounding is being handled, but also the addition of trailing zeroes.

    A different option would be to use an arbitrary precision library such as Big.js if precision is crucial (https://github.com/MikeMcl/big.js).

    Padding numbers

    We are sometimes faced with the need to pad numbers to a certain range. For example, suppose we want to display a number in five possible digits, such as 00042. One obvious solution would be to use the iterative approach and prepend characters, but there are a few cleaner solutions.

    Getting ready

    First, we need to take a look at some of the functions that we are going to use. Let's take a look at the Array.join(separator) method that can be applied to create joined text from a list of elements:

    new Array('life','is','life').join('*')

    This will result in life*is*life that shows fairly simple elements that are joined with a given separator. Another method that is of interest is Array.slice(begin[, end]) that returns a copy of a portion of an array. For our use, we are only interested in the begin parameter that can have both positive and negative values. If we use a positive value, it means that this will be the starting index for the slice using zero-based indexing; for example, consider the following line of code:

    new Array('a','b','c','d','e','f','g').slice(4);

    The preceding line of code will return an array with the elements 'e','f', and 'g'.

    If, on the other hand, using a negative value for the begin element indicates an offset from the end of the array, consider the same example using a negative value as follows:

    new Array('a','b','c','d','e','f','g').slice(-3);

    The result would be 'e','f','g', as we are slicing from the end.

    How to do it...

    Let's get back to our problem: how do we create a clean solution for prepending zeros to a number? For an iterative solution, we create a method that accepts the number, the size of the formatted result, and the character that will be used for padding; let's take '0' for example:

    function iterativeSolution(number,size,character) {

      var strNumber = number.toString(),

        len = strNumber.length,

     

        prefix = '';

      for (var i=size-len;i>0;i--) {

          prefix += character;

      }

    return prefix + strNumber;

    }

    Here we converted the number to a string in order to get the length of its representation; afterwards, we simply create prefix that will have the size–len characters of the character variable, and just return the resulting prefix + strNumber that is the string representation for that number.

    You may notice that in the case where size is smaller than len, the original number is returned, and this should probably be changed in order to have the function working for that corner case.

    Another way would be to use the Array.slice() method to achieve similar results:

    function sliceExample(number,prefix){

      return (prefix+number).slice(-prefix.length);

    }

    sliceExample(42,00000);

    This will just prepend a prefix to a number and slice off the extra '0' counting from the end, making the solution a lot cleaner and, additionally, enabling us to be more flexible around what will be part of the prefix. The downside of this is that we are manually constructing the prefix that will be part of the method call sliceExample(42,00000). In order to make this process automatic, we can make use of Array.join:

    function padNumber(number,size,character){

      var prefix = new Array(1 + size).join(character);

    We create an array of the expected size + 1 as on joining, we'll get the total array size-1 joined elements. This will construct the prefix with the expected size, and the other part will remain the

    Enjoying the preview?
    Page 1 of 1